/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.retry;

import han.bashe.business.ejbclient.LogEjbClient;
import han.bashe.business.pipeline.Handler;
import han.bashe.business.pipeline.PipelineContext;
import han.bashe.common.entity.BasheEntityConstants;
import han.bashe.common.entity.SoaRetryRecord;
import han.bashe.common.message.RequestHelper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author Kent
 */
public class RetryHandler extends Handler{
	private static Log logger = LogFactory.getLog(RetryHandler.class);
	@Override
	public void postProcess(PipelineContext ctx) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preProcess(PipelineContext ctx) {
		if(ctx.isRetry())
			return true;
		return false;
	}

	@Override
	public void process(PipelineContext ctx) {
		try{
			RequestHelper rh = new RequestHelper(ctx.getRequest());
			SoaRetryRecord rr = new SoaRetryRecord();
			rr.setMessageLogId(rh.getLogId());
			if(rh.isRetryData()){
				rr.setRetryData(rh.getBody());
			}
			rr.setRetryTime(String.valueOf(System.currentTimeMillis()));
			if(ctx.hasError()){
				rr.setStatus(BasheEntityConstants.STATUS_ERROR);
			}else
				rr.setStatus(BasheEntityConstants.STATUS_OK);
			String id = LogEjbClient.getLog().createRetryRecord(rr);
			ctx.setRetryRecordId(id);
		}catch (Exception e) {
		
			logger.error("RetryHandler.process() error",e);
			ctx.setError(e);
		
		}
		
	}

}
